const removeScript = (scriptId) => {
  const script = document.getElementById(scriptId);
  document.getElementsByTagName('head')[0].removeChild(script);
};

const clearFunction = (functionName) => {
  try {
    delete window[functionName];
  } catch (e) {
    window[functionName] = undefined;
  }
};

const requestWithJsonp = (url) => {
  return new Promise((resolve) => {
    let callbackFunction = 'callbackFunc' + Math.ceil(Math.random() * 100000000000000000);
    url += url.indexOf('?') === -1 ? '?' : '&';
    const jsonpScript = document.createElement('script');
    jsonpScript.setAttribute('src', `${url}callback=${callbackFunction}`);
    let scriptId = callbackFunction;
    jsonpScript.id = scriptId;
    document.getElementsByTagName('head')[0].appendChild(jsonpScript);

    window[callbackFunction] = function (data) {
      removeScript(scriptId);
      clearFunction(callbackFunction);
      resolve(data);
    };
  });
};

export default requestWithJsonp;
